<?php

namespace App\Console\Commands\Tasks;

use App\Enums\AppJumpEnum;
use App\Enums\StreamerEnum;
use App\Models\MainDB\MallOrders;
use App\Models\MainDB\MallProducts;
use App\Models\MainDB\Streamer\StreamerLevel;
use App\Models\MainDB\UserData;
use App\Services\Tools\HelperService;
use App\Services\Tools\RedisService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use App\Http\Controllers\Common\TaskController;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class StreamerLevelCommand extends Command
{
    //命令名
    protected $signature = 'task:streamer_week_level';

    //命令描述:主播每周等级
    protected $description = '主播每周等级';

    // 奖品ID
    private $productList = [];



    const MAX_LEVEL = 8;
    const SEND_PRODUCT_LEVEL = 7;

    public function __construct()
    {
        // todo 待产品确认线上商品ID

        $streamerLevelProductConfig = app('model_config')->getValue('STREAMER_LEVEL_PRODUCT');

        $this->productList = json_decode($streamerLevelProductConfig, true) ?? [];
        parent::__construct();
    }

    public function handle()
    {
        Log::info('主播开始评级');
        $redisLock = Cache::lock($this->signature, 1 * 3600);
        if (!$redisLock->get() && env('APP_ENV') == 'production') {
            return;
        }

        try {
            $productIds = [];
            foreach ($this->productList as $productConfig) {
                $productIds =array_merge($productIds, $productConfig);
            }
            $levelConfig = StreamerLevel::query()->orderBy('score', 'desc')->get();
            $products    = MallProducts::query()->whereIn('id', $productIds)->get();

            $productOrder = [];
            foreach ($products as $product) {
                $productOrder[$product['id']] = [
                    'product_id'   => $product['id'],
                    'expired_time' => Carbon::now()->endOfWeek()->getTimestamp(),
                    'add_time'     => Carbon::now()->getTimestamp(),
                    'category_id'  => $product['category_id']
                ];
            }
            UserData::query()->where([['streamer_level', '!=', 0]])->chunk(100, function ($users) use ($levelConfig, $productOrder) {
                foreach ($users as $userInfo) {
                    $weekLevel = 1;
                    foreach ($levelConfig as $levelInfo) {
                        // 超过
                        if ($userInfo['streamer_score'] > $levelInfo['score']) {
                            $weekLevel = $levelInfo['level'];
                            break;
                        }
                        //用户未达到V1的保级值 需要警告
                        $alter         = 0;
                        $lastWeekLevel = app('redis')->get(StreamerEnum::STREAM_LEVEL_CACHE_KEY . ':' .  $userInfo->user_id . "_" .  date('W', strtotime("-1 week")));

                        $lastLastWeekLevel = app('redis')->get(StreamerEnum::STREAM_LEVEL_CACHE_KEY . ':' .  $userInfo->user_id . "_" .   date('W', strtotime("-2 week")));

                        if ($lastLastWeekLevel == 1 && $lastWeekLevel == 1) {
                            $alter = 2;
                        } elseif ($lastWeekLevel == 1) {
                            $alter = 1;
                        }
                        app('redis')->set(StreamerEnum::STREAM_LEVEL_ALTER_CACHE_KEY. "_" . $userInfo->user_id, $alter, 'ex', 24 * 3600 * 7);

                    }
                    //保存用户每周等级
                    app('redis')->set(StreamerEnum::STREAM_LEVEL_CACHE_KEY . ':' .  $userInfo->user_id . "_" . date('W'), $weekLevel, 'ex', 24 * 3600 * 30);
                    //判断用户上周等级


                    // 修改信息
                    $userInfo['streamer_score']           = 0;
                    $userInfo['last_week_streamer_level'] = $userInfo['streamer_level'];
                    $userInfo['streamer_level']           = $weekLevel > $userInfo['streamer_level'] ? $userInfo['streamer_level'] + 1 : $weekLevel;
                    $userInfo['streamer_level'] > self::MAX_LEVEL && $userInfo['streamer_level'] = self::MAX_LEVEL;
                    $userInfo->save();

                    // 发送通知
                    app('model_user_news')->sendUserNews(
                        $userInfo['user_id'],
                        '每周评定结果',
                        "{$userInfo['nickname']}本周主播定级结果{$userInfo['streamer_level']}级，继续努力！",
                        0, 0, 0,
                        AppJumpEnum::SYSTEM_MESSAGE_SOURCE,
                        ['show_type' => AppJumpEnum::WEB_URL_MESSAGE_TYPE, 'h5_url' => env("APP_LINK") . AppJumpEnum::H5_JUMP_URL[AppJumpEnum::STREAMER_CENTER]]);

                    // 送奖品
                    if ($userInfo['streamer_level'] >= self::SEND_PRODUCT_LEVEL) {
                        $userOrders = [];
                        foreach ($this->productList as $productConfigIds) {
                            foreach ($productConfigIds as $productConfigId) {
                                $userOrders[] = array_merge($productOrder[$productConfigId], [
                                    'user_id_owner' => $userInfo['user_id'],
                                ]);
                            }
                        }
                        $userOrders && MallOrders::insert($userOrders);
                    }

                    // 清除用户缓存
                    RedisService::clearUserInfo($userInfo["user_id"]);
                }
            });
        } catch (\Throwable $e) {
            $redisLock->release();
            Log::error('处理异常-END' . json_encode(['errMsg' => $e->getMessage()]));
        }
    }

}